using UnityEngine;

public abstract class Unit: MonoBehaviour
{
    [SerializeField] private ActionSO[] m_Actions;
    public bool IsMoving;
    public bool IsTargeted; // 是否被选中
    protected Animator m_Animator;
    protected AIPawn m_AIPawn;
    protected SpriteRenderer m_SpriteRenderer;
    protected Material m_OriginalMaterial;
    protected Material m_HighlightMaterial;

    public ActionSO[] Actions => m_Actions;

    protected void Awake()
    {
        // 并非所有单位都有动画控制器,最好还是用下面的if
        // m_Animator = GetComponent<Animator>();
        if (TryGetComponent<Animator>(out var animator))
        {
            m_Animator = animator;
        }

        if (TryGetComponent<AIPawn>(out var aiPawn))
        {
            m_AIPawn = aiPawn;
        }

        m_SpriteRenderer = GetComponent<SpriteRenderer>(); // 获取SpriteRenderer组件,所有对象都有
        m_OriginalMaterial = m_SpriteRenderer.material; // 保存原始材质
        m_HighlightMaterial = Resources.Load<Material>("Materials/Outline"); // 加载高亮材质,需要建立对应目录
    }

    public void MoveTo(Vector3 destination)
    {
        var direction = (destination - transform.position).normalized; // 获取方向,并归一化
        m_SpriteRenderer.flipX = direction.x < 0; // 根据方向设置翻转
        m_AIPawn.SetDestination(destination); // 设置目的地
    }

    public void Select()
    {
        Highlight();
        IsTargeted = true;
    }

    public void Deselect()
    {
        UnHighlight();
        IsTargeted = false;
    }

    void Highlight()
    {
        m_SpriteRenderer.material = m_HighlightMaterial;
    }

    void UnHighlight()
    {
        m_SpriteRenderer.material = m_OriginalMaterial;
    }

}